<?php
declare (strict_types = 1);

namespace app\controller;



use app\common\model\Content;
use app\service\ContentService;
use QL\QueryList;
use think\facade\Request;
use FFMpeg;

class Upload extends Common
{
    public function __construct()
    {
        parent::__construct();
    }

    //微信小程序上传
    public function upload_xcx(){
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file();
        try {
            validate(['image'=>'filesize:10240|fileExt:jpg,gif,jpeg,png,ico|image:200,200,jpg'])
                ->check($file);
            $file = request()->file("file");
            // 上传到本地服务器
            $savename = \think\facade\Filesystem::disk('upload')->putFile( 'avatar', $file);
            $savename = '/data/upload/'.$savename; //Request::domain().
            return $savename;
        } catch (think\exception\ValidateException $e) {
            return json(["code"=>40000,"msg"=>$e->getMessage()]);
        }
    }

    public function upload(){
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file();
        try {
            validate(['image'=>'filesize:10240|fileExt:jpg,gif,jpeg,png,ico|image:200,200,jpg'])
                ->check($file);
            $file = request()->file("file");
            // 上传到本地服务器
            $savename = \think\facade\Filesystem::disk('upload')->putFile( 'avatar', $file);
            //$suoluetu1_name = $this->th($savename);

            $savename = "/data/upload/".$savename; //Request::domain().
            return json(["code"=>200,"msg"=>"成功","data"=>$savename]);
        } catch (think\exception\ValidateException $e) {
            return json(["code"=>40000,"msg"=>$e->getMessage()]);
        }
    }

    //layui 富文本上传接口
    public function layedit(){
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file();
        try {
            validate(['image'=>'filesize:10240|fileExt:jpg,gif,jpeg,png,ico|image:200,200,jpg'])
                ->check($file);
            $file = request()->file("file");
            // 上传到本地服务器
            $savename = \think\facade\Filesystem::disk('upload')->putFile( 'avatar', $file);
            //$suoluetu1_name = $this->th($savename);

            $savename = "/data/upload/".$savename; //Request::domain().
            $img["src"] = $savename;
            $img["title"] = "米醋儿网上传的图片";
            return json(["code"=>0,"msg"=>"成功","data"=>$img]);
        } catch (think\exception\ValidateException $e) {
            return json(["code"=>40000,"msg"=>$e->getMessage()]);
        }
    }

    public function uploadword(){
        $file = request()->file("file");
        // 上传到本地服务器
        $savename = \think\facade\Filesystem::disk('upload')->putFile( 'word', $file);

        $shotrname = time().".txt"; // 短名称
        $savename = "/www/wwwroot/micuer.com/data/upload/".$savename; //Request::domain().
        $python_file_name = "/www/wwwroot/micuer.com/pythoncode/WordToHtml.py";

        //组装命令
        $cmd = "python {$python_file_name} ".$savename." {$shotrname}  2>error.txt 2>&1";
        $res = exec($cmd,$array, $ret);
        $str = $array[0];

        //$pa = '%<body(.*?)</body>%si';
        //$str = preg_match($pa,$str,$matches);


        $ql = QueryList::html($str);
        $body = $ql->find('body')->html();
        $matches[0] = $body;



        //将base64 图片保存到本地
        $html = $matches[0];
        $ql = QueryList::html($html);
        $data2 = $ql->find('img')->attrs('src');
        $imgs = $data2->all();

        foreach ($imgs as $k => $v){
            //$str = '';
            //base64 图片只需要 data:image/png;base64, 后面的内容
            $temp = substr($v,strpos($v,",") + 1); //base64 图片串
            $dir =  "./public/wordToHtmlImg/".date("Ymd").'/';
            if(!is_dir($dir)){
                mkdir($dir);
            }
            $name =$dir.uniqid('micuer',true).".png";
            file_put_contents($name,base64_decode($temp));
            $pix = substr($v,0,strpos($v,",") +1 ); //base64 图片串 前面的data:image/png;base64,
            $str = $pix.$temp; // 组合原来的base64的串
            //$name = './dsadasdadasdsa.png' 返回给前端组合成 $name = '/dsdadadas.png'
            $name = str_replace("./","/",$name); //base64 图片串
            $matches[0] = str_replace($str,$name,$matches[0]);
        }


        return json(["code"=>200,"msg"=>"成功","data"=>$savename,"cmd"=>$cmd,"array"=>$matches]);
    }

    public function wang_editor_upload(){
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file();
        try {
            validate(['image'=>'filesize:10240|fileExt:jpg,gif,jpeg,png,ico|image:200,200,jpg'])
                ->check($file);
            $file = request()->file("file");
            // 上传到本地服务器
            $savename = \think\facade\Filesystem::disk('upload')->putFile( 'avatar', $file);


            $savename = "/data/upload/".$savename; //Request::domain().
            return json(["errno"=>0,"msg"=>"成功","data"=>[$savename]]);
        } catch (think\exception\ValidateException $e) {
            return json(["code"=>40000,"msg"=>$e->getMessage()]);
        }
    }

    //多图上传
    public function uploads(){
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file();


        try {
            validate(['image'=>'filesize:10240|fileExt:jpg,gif,jpeg,png,ico|image:200,200,jpg'])
                ->check($file);
            $file = request()->file("file");
            $name =  $file->getOriginalName();
            // 上传到本地服务器
            $savename = \think\facade\Filesystem::disk('gaoqing')->putFile( '', $file);
            $path = "./data/upload/gaoqing/".$savename;
            $savename = Request::domain()."/data/upload/gaoqing/".$savename;

            //缩略图
            $image = \think\Image::open($path);
            // 按照原图的比例生成一个最大为150*150的缩略图并保存为thumb.png
            $suoluetu1_name = $path.uniqid()."150.png";
            $image->thumb(150, 150)->save($suoluetu1_name);
            $suoluetu1_name = substr($suoluetu1_name,1,strlen($suoluetu1_name));
            //缩略图


            return json(["code"=>200,"msg"=>"成功","data"=>$savename,"oname"=>$name,"suoluetu"=>$suoluetu1_name]);
        } catch (think\exception\ValidateException $e) {
            return json(["code"=>40000,"msg"=>$e->getMessage()]);
        }
    }

    //小视频上传
    public function minvideo(){
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file();

        try {

            validate(['image'=>'filesize:10240|fileExt:mp4,3gp,avi|image:200,200,jpg'])
                ->check($file);
            $file = request()->file("file");
            $name =  $file->getOriginalName();
            $ext = $file->getOriginalExtension();
            $name = str_replace($ext,'',$name);
            $name = str_replace('.','',$name);
            $size = $file->getSize();
            // 上传到本地服务器
            $savename = \think\facade\Filesystem::disk('minvideo')->putFile( '', $file);
            $path = "./data/upload/minvideo/".$savename;
            $savename = "/data/upload/minvideo/".$savename;


            //视频截图
            $configuration = array(
                'ffmpeg.binaries'  => '/usr/bin/ffmpeg',
                'ffprobe.binaries' =>  '/usr/bin/ffprobe'
            );
            $ffmpeg = FFMpeg\FFMpeg::create($configuration);
            $video = $ffmpeg->open($path);
            $res = $video
                ->frame(FFMpeg\Coordinate\TimeCode::fromSeconds(2))
                ->save($path."_jietu.png");
            $cover = $savename."_jietu.png"; //自动截图


            //保存信息
            $data["name"] = $savename;//保存的文件名
            $data["original_name"] = $name;//原文件名
            $data["title"] = $name;//原文件名
            $data["size"] = $size;
            $data["status"] = 2; //草稿
            $data["model_id"] = 2; //视频
            $data["user"] = $this->user;
            $data["prefimg"] = $cover;
            $data["imgs"] = json_encode([$cover]);//这里是一张图的数组
            $data["content"] = $savename;
            $data["type_id"] = 2;//本地视频
            $res = ContentService::save_video($data);//res 是保存的id
            $data = Content::with(['v'])->find($res);//查询并返回前台

            return json(["code"=>200,"msg"=>"成功","data"=>$data]);
        } catch (think\exception\ValidateException $e) {
            return json(["code"=>40000,"msg"=>$e->getMessage()]);
        }
    }

    //生成缩略图
    public function th($savename,$w=150,$h=150)
    {
        //缩略图S
        $path = "./data/upload/".$savename;
        $image = \think\Image::open($path);
        // 按照原图的比例生成一个最大为150*150的缩略图并保存为thumb.png
        $suoluetu1_name = $path.uniqid()."150.png";
        $image->thumb(150, 150)->save($suoluetu1_name);
        $suoluetu1_name = substr($suoluetu1_name,1,strlen($suoluetu1_name));
        return $suoluetu1_name;
        //缩略图E
    }

    //editor md拖拽上传
    public function mdeditor()
    {
        $file = request()->file();
        try {
            validate(['image'=>'filesize:10240|fileExt:jpg,gif,jpeg,png|image:200,200,jpg'])
                ->check($file);
            $file = request()->file("file");
            // 上传到本地服务器
            $savename = \think\facade\Filesystem::disk('upload')->putFile( 'avatar', $file);
            $savename = Request::domain()."/data/upload/".$savename;
            //return json(["code"=>200,"msg"=>"成功","data"=>$savename]);
            $arr = [
                // success : 0 | 1,           // 0 表示上传失败，1 表示上传成功
                // message : "提示的信息，上传成功或上传失败及错误信息等。",
                // url     : "图片地址"        // 上传成功时才返回
                'success'=>1,
                'message'=>"成功",
                'url'=>$savename
            ];
            die(json_encode($arr));
        } catch (think\exception\ValidateException $e) {
            return json(["code"=>40000,"msg"=>$e->getMessage()]);
        }

    }

    //editor md黏贴上传  从内存中黏贴
    public function paste_up()
    {
        $base64 = input('base');
        $base64 = str_replace("data:image/png;base64,","",$base64);
        $base64 = str_replace("data:image/jpg;base64,","",$base64);
        $base64 = str_replace("data:image/gif;base64,","",$base64);
        $base64 = str_replace("data:image/jpeg;base64,","",$base64);
        $file = base64_decode($base64);
        $date = date("Ymd");
        $path = "./data/upload/".$date."/";
        $filename = $path.uniqid().".png";
        if(!is_dir($path)){
            mkdir($path,0755);
        }
        $img = file_put_contents($filename,$file);

        $savename = Request::domain()."/".$filename;
        $savename = str_replace("./","",$savename);
        $arr = [
            // success : 0 | 1,           // 0 表示上传失败，1 表示上传成功
            // message : "提示的信息，上传成功或上传失败及错误信息等。",
            // url     : "图片地址"        // 上传成功时才返回
            'code'=>1,
            'msg'=>"成功",
            'url'=>$savename
        ];
        return json($arr);
    }

}
